package com.plum.admin.modules.social.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.plum.admin.common.constant.Constant;
import com.plum.admin.common.util.R;
import com.plum.admin.modules.social.entity.SysSocial;
import com.plum.admin.modules.social.service.ISysSocialService;
import com.plum.admin.modules.social.service.impl.GiteeLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * TODO
 *
 * @author 子丶沫
 * @version 1.0
 * @date 2021/10/12 16:11
 */
@Controller
@RequestMapping("/social/gitee")
public class GiteeLoginController {

    @Value("${social.gitee.callbackUrl}")
    private String callbackUrl;
    @Value("${social.callbackFeUrl}")
    private String callbackFeUrl;
    @Autowired
    private GiteeLoginService giteeLoginService;
    @Autowired
    private ISysSocialService sysSocialService;

    @GetMapping("/login")
    @ResponseBody
    public R<Object> login(){
        return R.ok(giteeLoginService.getAuthorizeUrl(callbackUrl));
    }
    @GetMapping("/callback")
    public String callback(@RequestParam String code){
        if(StrUtil.isBlank(code)){
            return "redirect:" + callbackFeUrl + "?error=" + URLUtil.encode("您未同意授权", "utf-8");
        }
        String accessToken = giteeLoginService.getAccessToken(code, callbackUrl);
        SysSocial sysSocial = giteeLoginService.getUserInfo(accessToken);
        SysSocial social = sysSocialService.findSocialByOpenId(sysSocial.getOpenId(), Constant.SOCIAL_TYPE_GITEE);
        if(ObjectUtil.isNull(social)){
            sysSocialService.save(sysSocial);
        }
        return "redirect:"+sysSocialService.getOauthLoginUrl(sysSocial,social,Constant.SOCIAL_TYPE_GITEE);
    }
}
